#include "ConsoleWidget.h"
#include <QKeyEvent>
#include <QFontDatabase>

ConsoleWidget::ConsoleWidget(QWidget *parent)
    : QWidget(parent)
{
    setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
    setWindowTitle(QStringLiteral("Qt 内置控制台"));
    resize(640, 360);

    output = new QPlainTextEdit(this);
    output->setReadOnly(true);
    // 设置等宽字体，便于阅读
    QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont);
    output->setFont(mono);

    input = new QLineEdit(this);
    input->setFont(mono);
    input->setPlaceholderText(QStringLiteral("输入命令，回车执行；↑/↓ 浏览历史；Tab 补全"));

    auto *layout = new QVBoxLayout(this);
    layout->setContentsMargins(6,6,6,6);
    layout->addWidget(output);
    layout->addWidget(input);
    setLayout(layout);

    // 自动补全
    cmdModel = new QStringListModel(this);
    completer = new QCompleter(cmdModel, this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setCompletionMode(QCompleter::PopupCompletion);
    input->setCompleter(completer);

    connect(input, SIGNAL(returnPressed()), this, SLOT(onReturnPressed()));
}

void ConsoleWidget::onReturnPressed()
{
    const QString cmd = input->text().trimmed();
    if (cmd.isEmpty()) return;

    // 保存历史（去重相邻重复）
    if (history.isEmpty() || history.last() != cmd)
        history << cmd;
    historyIndex = history.size();

    input->clear();
    emit commandEntered(cmd);
}

void ConsoleWidget::appendOutput(const QString &text)
{
    output->appendPlainText(text);
}

void ConsoleWidget::setCommandList(const QStringList &cmds)
{
    cmdModel->setStringList(cmds);
}

void ConsoleWidget::keyPressEvent(QKeyEvent *event)
{
    // 让 ↑/↓ 在输入框上也能切换历史
    if (event->key() == Qt::Key_Up) {
        if (!history.isEmpty() && historyIndex > 0) {
            historyIndex--;
            input->setText(history.at(historyIndex));
            input->setCursorPosition(input->text().size());
        }
        return;
    } else if (event->key() == Qt::Key_Down) {
        if (!history.isEmpty() && historyIndex < history.size() - 1) {
            historyIndex++;
            input->setText(history.at(historyIndex));
            input->setCursorPosition(input->text().size());
        } else {
            historyIndex = history.size();
            input->clear();
        }
        return;
    }
    QWidget::keyPressEvent(event);
}
/*
    ConsoleServer::instance()->init(9000);      // 开启 UDP 控制台（可选）
    ConsoleServer::instance()->enableLocalConsole(true); // 启用本地控制台（Ctrl+`）
    MainWindow w;
    ConsoleServer::instance()->showConsole();
    w.show();
    ConsoleServer::instance()->attachShortcut(&w);
*/
